const Koa = require('koa');// 引入koa框架
const app = new Koa();// 实例化koa应用
const cors = require('@koa/cors');// 解决跨域问题
const bodyParser = require('koa-bodyparser');// 解析http请求的消息体
const json = require('koa-json');// 将http响应的数据转化为json格式
const { addAliases } = require("module-alias");// 配置模块别名
const { spawn } = require('child_process');// 用于启动子进程
const path = require('path');// 路径处理

addAliases({
    "@": __dirname
});

// MCP服务管理
let mcpProcess = null;
let mcpRequestId = 1;
let pendingRequests = new Map();

// 启动MCP服务
function startMcpService() {
    const mcpPath = path.join(__dirname, '12306-mcp', 'build', 'index.js');
    console.log('正在启动12306-mcp服务...');
    
    mcpProcess = spawn('node', [mcpPath], {
        stdio: ['pipe', 'pipe', 'pipe'],
        cwd: path.join(__dirname, '12306-mcp')
    });

    let responseBuffer = '';

    mcpProcess.stdout.on('data', (data) => {
        responseBuffer += data.toString();
        
        // 处理完整的JSON响应
        const lines = responseBuffer.split('\n');
        responseBuffer = lines.pop() || ''; // 保留不完整的行
        
        for (const line of lines) {
            if (line.trim()) {
                try {
                    const response = JSON.parse(line.trim());
                    if (response.id && pendingRequests.has(response.id)) {
                        const { resolve } = pendingRequests.get(response.id);
                        pendingRequests.delete(response.id);
                        resolve(response);
                    }
                } catch (error) {
                    console.log(`[12306-MCP] ${line.trim()}`);
                }
            }
        }
    });

    mcpProcess.stderr.on('data', (data) => {
        console.log(`[12306-MCP Error] ${data.toString().trim()}`);
    });

    mcpProcess.on('close', (code) => {
        console.log(`12306-mcp服务已停止，退出代码: ${code}`);
        mcpProcess = null;
        // 拒绝所有待处理的请求
        for (const [id, { reject }] of pendingRequests) {
            reject(new Error('MCP服务已关闭'));
        }
        pendingRequests.clear();
    });

    mcpProcess.on('error', (error) => {
        console.error('启动12306-mcp服务失败:', error);
        mcpProcess = null;
    });

    console.log('12306-mcp服务已启动');
    
    // 等待一段时间让MCP服务完全启动
    setTimeout(async () => {
        try {
            // 初始化MCP连接
            const initResponse = await callMcpService('initialize', {
                protocolVersion: '2024-11-05',
                capabilities: {
                    roots: {
                        listChanged: false
                    }
                },
                clientInfo: {
                    name: 'travel-assistant',
                    version: '1.0.0'
                }
            });
            console.log('MCP服务初始化成功');
            
            // 发送initialized通知
            await callMcpService('initialized', {});
            console.log('MCP服务连接建立完成');
        } catch (error) {
            console.error('MCP服务初始化失败:', error);
        }
    }, 2000);
}

// 调用MCP服务
function callMcpService(method, params) {
    return new Promise((resolve, reject) => {
        if (!mcpProcess) {
            reject(new Error('MCP服务未启动'));
            return;
        }

        const requestId = mcpRequestId++;
        const request = {
            jsonrpc: '2.0',
            id: requestId,
            method: method,
            params: params
        };

        pendingRequests.set(requestId, { resolve, reject });

        // 设置超时
        setTimeout(() => {
            if (pendingRequests.has(requestId)) {
                pendingRequests.delete(requestId);
                reject(new Error('MCP请求超时'));
            }
        }, 30000);

        mcpProcess.stdin.write(JSON.stringify(request) + '\n');
    });
}

// 导出MCP调用函数
global.callMcpService = callMcpService;

// 停止MCP服务
function stopMcpService() {
    if (mcpProcess) {
        console.log('正在停止12306-mcp服务...');
        mcpProcess.kill('SIGTERM');
        mcpProcess = null;
    }
}

// 优雅关闭处理
process.on('SIGINT', () => {
    console.log('正在关闭服务...');
    stopMcpService();
    process.exit(0);
});

process.on('SIGTERM', () => {
    console.log('正在关闭服务...');
    stopMcpService();
    process.exit(0);
});
// 接口
const router = require('@/router');// 引入路由
// 体统一接口响应数据格式
const responseHandler = require('@/config/result');// 引入响应体处理中间件
// 错误处理中间件
const errorHandler = require('@/config/errorhandler');

app.use(json());// 将http响应的数据转化为json格式
app.use(bodyParser());// 解析http请求的消息体
app.use(cors({
    origin: function (ctx) {
        // 允许所有来源
        return '*';
    },
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With', 'Origin'],
    credentials: false // 设置为false，避免与origin: '*'冲突
}));// 解决跨域问题
app.use(responseHandler);// 挂载响应体处理中间件
app.use(errorHandler);// 挂载错误处理中间件

app.use(router.routes()).use(router.allowedMethods());// 挂载路由

// 启动MCP服务
startMcpService();

app.listen(8080, '0.0.0.0');
console.log("服务已启动，端口号为8080!");
